<?php

namespace api\components;

use common\components\Exception;
use Yii;
use yii\base\Model;

class BaseModel extends Model
{
    /**
     * 获取模型错误
     * @param $model \yii\base\Model
     * @param bool $isThrow
     * @return bool|null
     * @throws Exception
     */
    public static function getErrorMessage($model, $isThrow = true)
    {
        $error = null;
        if ($model->hasErrors()) {
            $errors = $model->getErrors();
            foreach ($errors as $value) {
                $error = $value[0];
                break;
            }
        }
        if ($isThrow && !(null === $error)) {
            throw new Exception($error, true);
        } elseif (!$isThrow && !(null === $error)) {
            return $error;
        } else {
            return true;
        }
    }
}